<script setup lang="ts">
import MpHtml from 'mp-html/dist/uni-app/components/mp-html/mp-html.vue'
import { fetchCaseDetailAPI } from '@/apis/fetchCaseDetail'
import { submitCaseAPI } from '@/apis/submitCase'
import { useUserInfoStore } from '@/store/userInfo'
import modalSuccessIcon from '@/static/images/modal/success.png'

const userInfoStore = useUserInfoStore()

// 是否显示状态栏背景
const isShowNavBg = ref(false)
// 监听页面滚动，更新状态栏背景可见性
onPageScroll((e) => {
  const toggle = useThrottleFn(() => isShowNavBg.value = e.scrollTop > 16, 100)
  toggle()
})
// 将状态栏背景可见性提供给状态栏组件
provide(isShowNavigationBarBackgroundKey, isShowNavBg)

/* ------------------------------- 案例数据 START ------------------------------- */
// 当前页面的案例数据
const caseItem = ref<Case | null>(null)

// 案例轮播图数据
const images = computed(() => {
  return caseItem.value?.image?.split(',') || []
})

// 案例富文本数据
const richTextRawHtml = computed(() => {
  const ret = caseItem.value?.content?.replace(/&gt;/g, '>')
    .replace(/&lt;/g, '<')
    .replace(/&quot;/g, '"')
    .replace(/&apos;/g, '\'')
    .replace(/&amp;/g, '&')
  return ret
})

// 在加载时请求案例数据
onLoad(async (options) => {
  if (options && options.case_id) {
    try {
      const res = await fetchCaseDetailAPI(options.case_id)
      if (res.data?.code === 1)
        caseItem.value = res.data.data
      else
        uni.showToast({ title: res.data?.msg, icon: 'none' })
    }
    catch (err) {
      uni.showToast({ title: '获取数据失败', icon: 'none' })
    }
  }
  else {
    uni.showToast({ title: '获取数据失败', icon: 'none' })
  }
})
/* -------------------------------- 案例数据 END -------------------------------- */

/* -------------------------------- 表单 START -------------------------------- */
const formRef = ref<any>(null)

// 表单数据
const formData = ref({
  extent: '',
  mobile: '',
})

// 表单校验规则
const rules = {
  extent: [
    { required: true, message: '面积必须为数字', trigger: ['blur', 'change'] },
    { required: true, message: '密码不可为空', trigger: ['blur', 'change'] },
  ],
  mobile: [
    {
      pattern: /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/,
      message: '请输入正确的手机号',
      trigger: ['blur'],
    },
    { required: true, message: '手机号不可为空', trigger: ['blur', 'change'] },
  ],
}

// 是否显示表单提交成功弹窗
const isShowSuccessModal = ref(false)

/**
 * @description 处理提交表单事件
 */
const handleSubmit = useThrottleFn(() => {
  formRef.value.validate()
    .then(async () => {
      try {
        const res = await submitCaseAPI({
          case_id: `${caseItem.value?.id}`,
          extent: formData.value.extent,
          mobile: formData.value.mobile,
        }, userInfoStore.userInfo!.token!)
        if (res.data?.code === 1)
          isShowSuccessModal.value = true
        else
          uni.showToast({ title: res.data?.msg, icon: 'none' })
      }
      catch (err) {
        uni.showToast({ title: '提交失败', icon: 'none' })
      }
    })
    .catch((errors: AnyObject[]) => {
      uni.showToast({ title: errors[0].message, icon: 'none' })
    })
}, 1000)

/**
 * @description 处理关闭弹窗的事件
 */
function handleCloseSuccessModal() {
  isShowSuccessModal.value = false
}
/* --------------------------------- 表单 END --------------------------------- */
</script>

<template>
  <view class="min-h-screen">
    <!-- 自定义导航栏 -->
    <NavigationBar
      :is-show-background="isShowNavBg" title="案例详情" title-placement="center"
      text-color="#000000" :is-show-back-button="true"
    />
    <!-- 顶部轮播图 -->
    <swiper :list="images" :indicator="true" :style="{ height: '500rpx' }">
      <swiper-item v-for="image in images" :key="image">
        <uv-image :src="image" width="750rpx" height="500rpx" />
      </swiper-item>
    </swiper>
    <!-- 页面主体 -->
    <view class="z-1 relative -mt-30rpx pt-40rpx px-30rpx rounded-30rpx bg-white">
      <!-- 案例名称 & 介绍 -->
      <view class="flex flex-col">
        <view class="text-30rpx leading-30rpx text-primary font-bold">
          {{ caseItem?.name || '未知' }}
        </view>
        <Spacer height="20" />
        <view class="text-26rpx leading-26rpx text-tertiary">
          {{ caseItem?.introduction || '未知' }}
        </view>
        <Spacer height="30" />
      </view>
      <!-- 表单 -->
      <view class="flex flex-col rounded-30rpx overflow-hidden border-1px border-solid border-#FFC070">
        <view class="relative flex justify-center items-center h-120rpx bg-#FFC070 text-32rpx leading-32rpx text-white font-bold">
          免费预约同款设计
          <image
            class="absolute -right-5rpx top-50% -transform-translate-y-50% w-87rpx h-109rpx"
            src="@/static/images/caseDetail/case-form-icon.png"
          />
        </view>
        <uv-form ref="formRef" :model="formData" :rules="rules">
          <view class="flex flex-col m-30rpx">
            <uv-form-item prop="extent" :custom-style="{ padding: 0 }">
              <view class="flex items-center p-30rpx bg-#F8F8F8 rounded-10rpx">
                <view class="flex justify-between min-w-118rpx text-justify text-28rpx leading-28rpx text-secondary">
                  府邸面积
                </view>
                <Spacer width="40" />
                <input
                  v-model="formData.extent"
                  type="text"
                  class="text-28rpx leading-28rpx text-secondary"
                  placeholder="请输入您的面积"
                  placeholder-style="color: #999999"
                >
              </view>
            </uv-form-item>
            <Spacer height="20" />
            <uv-form-item prop="mobile" :custom-style="{ padding: 0 }">
              <view class="flex items-center p-30rpx bg-#F8F8F8 rounded-10rpx">
                <view class="flex justify-between min-w-118rpx text-justify text-28rpx leading-28rpx text-secondary">
                  电话
                </view>
                <Spacer width="40" />
                <input
                  v-model="formData.mobile"
                  type="text"
                  class="text-28rpx leading-28rpx text-secondary"
                  placeholder="请输入您的手机号"
                  placeholder-style="color: #999999"
                >
              </view>
            </uv-form-item>
            <Spacer height="40" />
            <RGButton @tap="handleSubmit">
              立即免费预约
            </RGButton>
          </view>
        </uv-form>
      </view>
      <Spacer height="40" />
      <!-- 富文本 -->
      <MpHtml :content="richTextRawHtml" />
      <Spacer height="80" />
    </view>
    <uv-overlay :show="isShowSuccessModal" @tap="handleCloseSuccessModal">
      <uv-transition mode="zoom-in" :show="isShowSuccessModal">
        <view style=" position: relative; width: 100vw; height: 100vh;">
          <JZTModal :icon="modalSuccessIcon" title="预约成功" content="" button-label="确定" @confirm="handleCloseSuccessModal" />
        </view>
      </uv-transition>
    </uv-overlay>
  </view>
</template>

<route lang="yaml">
name: 'caseDetail'
style:
  navigationStyle: 'custom'
layout: 'custom'
</route>
